package main

import (
	"context"
	"flag"
	"fmt"
	"grpc-example/data"
	"grpc-example/features/authentication"
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	ecpb "grpc-example/protobuf/echo"
)

var addr = flag.String("addr", "localhost:50051", "the address to connect to")

func callUnaryEcho(client ecpb.EchoClient, message string) {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message})
	// 调用时授权
	//myAuth := authentication.NewMyAuth("admin", "root")
	//resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message},grpc.PerRPCCredentials(myAuth))
	if err != nil {
		log.Fatalf("client.UnaryEcho(_) = _, %v: ", err)
	}
	fmt.Println("UnaryEcho: ", resp.Message)
}

func main() {
	flag.Parse()

	// 构建一个 PerRPCCredentials。
	// perRPC := oauth.NewOauthAccess(fetchToken())
	myAuth := authentication.NewMyAuth("admin", "root")
	creds, err := credentials.NewClientTLSFromFile(data.Path("x509/ca.crt"), "www.chauncy.com")
	if err != nil {
		log.Fatalf("failed to load credentials: %v", err)
	}

	// conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(perRPC))
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	conn, err := grpc.DialContext(ctx, *addr, grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(myAuth))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer cancel()
	defer conn.Close()
	client := ecpb.NewEchoClient(conn)

	callUnaryEcho(client, "hello world")
}
